# -*- coding: utf-8 -*-
"""
Created on Mon Aug 07 10:00:27 2017

@auth
"""
#%%
import os
import sys
import logging
import traceback
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import StaleElementReferenceException, NoSuchElementException, NoSuchWindowException
from selenium.webdriver.support import expected_conditions as EC
from logging.handlers import RotatingFileHandler

sys.path.append("../")

bizModule = "baidu_map_base"
logFileDir = "../log/%s/" % (bizModule)
if not os.path.exists(logFileDir):
    os.makedirs(logFileDir)
logger = logging.getLogger(bizModule)
hdlr = RotatingFileHandler(logFileDir + 'info.log', "a", 20 * 1024 * 1024, 20, "utf-8")
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)

class BaiduMap():

    def __init__(self, username, password):
        self.username = username
        self.password = password

        # 设置浏览器
        # self.baseurl = "https://www.tianyancha.com/login"
        # self.browser = webdriver.Firefox()
        # self.ip_port = {'ip': ["111.62.251.107", "183.136.218.253", "182.16.69.196", "111.13.7.121", "183.169.128.30", "111.13.7.119", "124.165.252.72", "47.89.22.200", "111.13.7.123", "125.77.25.116", "120.199.224.78", "219.239.142.253", "61.136.163.245", "121.248.112.20", "125.77.25.124"],
        #                'port': [8080, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 3128, 3128, 3128, 80]}
        self.baseurl = "https://map.baidu.com/"
        #number = np.random.randint(1, 15)
        profile = webdriver.FirefoxProfile()
        #profile.set_preference('network.proxy.type', 1)
        #profile.set_preference('network.proxy.http', self.ip_port['ip'][number])  # '183.222.102.104'
        #profile.set_preference('network.proxy.http_port', self.ip_port['port'][number])  # int  8080
        #profile.set_preference("permissions.default.image", 2)
        #profile.set_preference("dom.ipc.plugins.enabled.libflashplayer.so", False)
        profile.update_preferences()
        self.browser = webdriver.Firefox(firefox_profile=profile)  # 火狐浏览器
        self.browser.get(self.baseurl)
        self.browser.set_page_load_timeout(240)
        self.browser.set_script_timeout(60)
        self.action = ActionChains(self.browser)
    
    def is_element_visible(self, element):
        browser = self.browser
        try:
            the_element = EC.visibility_of_element_located(element)
            assert the_element(browser)
            flag = True
        except:
            flag = False
        return flag        

    def isElementExist(self, element):
        flag = True
        try:
            browser = self.browser
            browser.find_element_by_xpath(element)
            return flag
        except:
            flag = False
            return flag    
    
    def find_elements_by_xpath(self, xpath):
        browser = self.browser
        max_retry = 5
        cur_retry_num = 1
        while cur_retry_num <= max_retry:
            try:
                return browser.find_elements_by_xpath(xpath)
            except StaleElementReferenceException:
                print(u"页面元素没有找到，进行第%d重试" % (cur_retry_num))
                browser.implicitly_wait(3)
            finally:
                cur_retry_num += 1

    def find_element_by_xpath(self, xpath):
        browser = self.browser
        max_retry = 5
        cur_retry_num = 1
        while cur_retry_num <= max_retry:
            try:
                return browser.find_element_by_xpath(xpath)
            except StaleElementReferenceException:
                print(u"页面元素没有找到，进行第%d重试" % (cur_retry_num))
                browser.implicitly_wait(3)
            finally:
                cur_retry_num += 1     

    def turnhandle(self):
        browser = self.browser
        browser.switch_to_window(browser.window_handles[-1])                

    def login(self):
        loginSuccess = True
        # browser = self.browser
        # try:
        #     browser.get(self.baseurl)
        # except:
        #     browser.execute_script('window.stop()')
        # account = {'user': self.username, 'password': self.password}
        # try:
        #     # 切换到账号密码登录
        #     browser.implicitly_wait(5)
        #     iframe = browser.find_element_by_xpath("//div[@id='loginchina']/iframe")
        #     browser.switch_to_frame(iframe)
        #     browser.find_element_by_id("J_Quick2Static").click()
        #     option1 = browser.find_element_by_xpath('//input[@id = "TPL_username_1"]')
        #     option2 = browser.find_element_by_xpath('//input[@id = "TPL_password_1"]')
        #     #option3 = browser.find_element_by_xpath('//button[@id="J_SubmitStatic"]')
        #     option1.send_keys(account['user'])
        #     option2.send_keys(account['password'])
        #     browser.implicitly_wait(5)
        #     order = raw_input(u"请完成滑动滑块的动作后，手动点击登录，按任意键+回车后继续运行".encode("gbk"))
        #     print(u"登陆成功，最大化")
        #     #option3.click()
        #     loginSuccess = True
        # except Exception as e:
        #     print(u"登陆失败")
        #     print('str(Exception):\t', str(Exception))
        #     print('str(e):\t\t', str(e))
        #     print('repr(e):\t', repr(e))
        #     print('e.message:\t', e.message)
        #     print('traceback.print_exc():')
        #     traceback.print_exc()
        #     print('traceback.format_exc():\n%s' % traceback.format_exc())
        #     browser.execute_script('window.stop()')
        # print(u"登陆成功，删除广告并最大化，若未删除，请删除后继续运行")
        # # 最大化
        # browser.maximize_window()
        return loginSuccess
